package com.twm.boot;

import com.twm.handler.UserServiceHandler;
import com.twm.serializer.JSONSerializer;
import com.twm.serializer.RpcDecoder;
import com.twm.serializer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ServerBoot {

    /*public static void main(String[] args) throws InterruptedException {
        startServer("127.0.0.1", "8999");
    }*/

    public static void startServer(String ip, String port) throws InterruptedException {
        //1、创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2、创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(Object.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(Object.class, new JSONSerializer()));
                        //把我们自定义的CHannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        serverBootstrap.bind(8999).sync();
    }
}
